import 'dart:async';

import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/generated/json/base/json_convert_content.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/page/home/model/city_entity.dart';
import 'package:tender_flutter/utils/sputils.dart';

typedef void OnLocationChangeListener(CityEntity cityEntity, bool refresh);

/// 高德定位
class AMapLocationUtils {
  static OnLocationChangeListener listener;

  AMapLocationUtils._intrnal();

  static init() async {
    await AmapLocation.instance.init(iosKey: AppConfig.AMap_appkey_ios);
  }

  ///开始定位
  static void startLocation(listener) async {
    /// 定位之前 申请权限
    if (await requestLocationPermission()) {
      AmapLocation.instance.fetchLocation(needAddress: true).then((value) {
        Location location = value;
        ApiCommon.getCityByCodeOrName(
                title: location.city, code: location.cityCode)
            .then((value) {
          ApiResponse<CityEntity> response = value;
          CityEntity cityEntity;
          if (response.status == Status.SUCCESS) {
            cityEntity = response.result;
          } else {
            Map<String, dynamic> c = {
              "id": int.parse(location.cityCode),
              "code": location.cityCode,
              "title": location.city
            };
            cityEntity = JsonConvert.fromJsonAsT(c);
          }

          bool refresh = false;
          if (DataManager.instance.cityEntity == null) {
            /// 定位信息全局化
            DataManager.instance.cityEntity = cityEntity;

            /// 序列化定位信息
            SPUtils.saveAddres(cityEntity);
            refresh = true;
          } else if (cityEntity.title !=
              DataManager.instance.cityEntity.title) {
            refresh = true;

            /// 序列化定位信息
            SPUtils.saveAddres(cityEntity);
          }

          listener(cityEntity, refresh);
          // /// 定位信息全局化
          // DataManager.instance.cityEntity = cityEntity;
          //
          // // 如果保存的地理位置信息和定位的一直 则不需要回调进行刷新数据
          // bool refresh = (DataManager.instance.cityEntity == null ||
          //         cityEntity.title != DataManager.instance.cityEntity.title)
          //     ? true
          //     : false;
          //
          // listener(cityEntity, refresh);
          //
          // /// 序列化定位信息
          // SPUtils.saveAddres(cityEntity);
        });
      });
    } else {
      print("定位权限申请不通过");
    }
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  static Future<bool> requestLocationPermission() async {
    //获取当前的权限
    final permissions = await Permission.location.request();

    // if (permissions.isGranted) {
    //   return true;
    // } else {
    //   ToastUtils.show("需要定位权限");
    //   return false;
    // }

    if (await permissions.isGranted) {
      print("用户定位同意了");
      return true;
    } else if (await permissions.isDenied) {
      print("用户定位拒绝了");
      // ToastUtils.show("需要定位权限");
      return false;
    } else if (await permissions.isPermanentlyDenied) {
      print("用户定位永久拒绝");
      // ToastUtils.show("需要定位权限");
      return false;
    }
  }
}
